package com.hebeu.core.util;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;

public class HibernateDao<T> {
	protected HibernateSessionFactory hsf;
	protected Class<T> entityClass;

	@SuppressWarnings("unchecked")
	public HibernateDao() {
		//this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
		entityClass =(Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}

	public void save(final T entity) {
		 //getSession().saveOrUpdate(entity);
		Session s = getSession();
		Transaction tx = s.beginTransaction();
		s.save(entity);
		tx.commit();
		s.close();
	}

	public void delete(final T entity) {
		Session s = getSession();
		Transaction tx = s.beginTransaction();
		s.delete(entity);
		tx.commit();
		s.close();
	}

	public void deleteById(int id) {
		delete(get(id));
	}

	@SuppressWarnings("unchecked")
	public T get(int id) {
		return (T) getSession().load(entityClass, id);
		 
	}

	public List<T> getList(String hql) {
		Session s = getSession();
		Transaction tx = s.beginTransaction();
		Query q = s.createQuery(hql);
		List<T> list = q.list();
		tx.commit();
		s.close();
		return list;
	}

	public List<T> getAll() {
		return find();
	}
	
	public List<T> find(final Criterion... criterions) {
		return createCriteria(criterions).list();
	}
	
	public Criteria createCriteria(final Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(entityClass);
		for (Criterion c : criterions) {
			criteria.add(c);
		}
		return criteria;
	}

}
